import { Model, DataTypes } from 'sequelize';
import SequelizeClient from '../sequelizeclient';
import VDetail, { VoucherDetail } from './VoucherDetail';
let sequelize = SequelizeClient.getInstance();
import common from '../common';
//凭证主表
export class Voucher extends Model {}
const init = () => {
  Voucher.init(
    {
      voucherType: DataTypes.INTEGER, // 1记 2转 3贷 4付
      borrow: DataTypes.DECIMAL, //借方累计金额
      loan: DataTypes.DECIMAL, //贷方累计金额
      voucherDate: DataTypes.STRING, //记账日期 yyyy-MM-dd 格式
      sort: DataTypes.INTEGER, //记号  按type ,日期+1
    },
    { sequelize, modelName: 'voucher' },
  );
  VDetail.init();
  Voucher.VoucherDetails = Voucher.hasMany(VoucherDetail, {
    as: 'voucherDetails',
  });
  VoucherDetail.belongsTo(Voucher);
};

const insert = async item => {
  try {
    if (item.voucherDetails == null || item.voucherDetails.length <= 1) {
      return { success: false, message: '凭证数据有误！' };
    }
    let one = await Voucher.findOne({
      raw: true,
      where: { voucherType: item.voucherType, voucherDate: item.voucherDate },
      order: [['sort', 'desc']],
    });
    if (!one) {
      item.sort = 1;
    } else {
      item.sort = one.sort + 1;
    }
    let result = await Voucher.create(item, {
      include: [Voucher.VoucherDetails],
    });
    return { success: true, message: '保存成功！' };
  } catch (error) {
    return { success: false, message: '出现意外错误！' + error };
  }
};
const getPages = async pages => {
  console.log(pages);
};
const getTopSort = async item => {
  if (item.voucherType == null || item.voucherDate == null) {
    return { success: false, message: '参数错误' };
  }
  let one = await Voucher.findOne({
    raw: true,
    where: { voucherType: item.voucherType, voucherDate: item.voucherDate },
    order: [['sort', 'desc']],
  });
  if (!one) {
    return 1;
  } else {
    return one.sort + 1;
  }
};

export default {
  init,
  insert,
  getTopSort,
  getPages,
};
